package com.oos.zone.aware;

import cn.binarywang.wx.miniapp.api.WxMaService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

/**
 * 功能描述：Bean后置处理器
 *
 * @author 拓金辉
 * @version 1.0
 * @date 2021-08-12 09:38:05
 */
@Component
public class AwareBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessBeforeInitialization(@Nonnull Object bean, @Nonnull String beanName) throws BeansException {
        if (bean instanceof Aware) {
            if (bean instanceof InitWechatCpConfigAware) {
                WxCpService wxCpService = applicationContext.getBean(WxCpService.class);
                ((InitWechatCpConfigAware) bean).initWxCpConfig(wxCpService);
            }
            if (bean instanceof InitWechatMaConfigAware) {
                WxMaService wxMaService = applicationContext.getBean(WxMaService.class);
                ((InitWechatMaConfigAware) bean).initWxMaConfig(wxMaService);
            }
            if (bean instanceof InitWechatMpConfigAware) {
                WxMpService wxMpService = applicationContext.getBean(WxMpService.class);
                ((InitWechatMpConfigAware) bean).initWxMpConfig(wxMpService);
            }
        }
        return bean;
    }

    @Override
    public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
